package com.srwl.easeui.widget;

import android.content.Context;
import android.text.Editable;
import android.text.InputFilter;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.text.style.ImageSpan;
import android.util.AttributeSet;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;

import com.srwl.mytx.R;
import com.srwl.mytx.utils.MoonUtils;


/**
 * primary menu
 */
public class EaseChatPrimaryMenu extends EaseChatPrimaryMenuBase implements OnClickListener {
    private static final String TAG = "EaseChatPrimaryMenu";
    private EditText editText;
    private View buttonSetModeKeyboard;
    private RelativeLayout edittext_layout;
    private View buttonSetModeVoice;
    private View buttonSend;
    private View buttonPressToSpeak;
    private ImageView faceNormal;
    private ImageView faceChecked;
    private Button buttonMore;
    private RelativeLayout faceLayout;
    private Context context;

    public EaseChatPrimaryMenu(Context context, AttributeSet attrs, int defStyle) {
        //super(context, attrs, defStyle);
        //  init(context, attrs);
        this(context, attrs);
    }

    public EaseChatPrimaryMenu(Context context, AttributeSet attrs) {
        //  this(context, attrs, 0);
        super(context, attrs);
        init(context, attrs);
    }

    public EaseChatPrimaryMenu(Context context) {
        super(context);
        init(context, null);
    }

    private void init(final Context context, AttributeSet attrs) {
        this.context = context;
        LayoutInflater.from(context).inflate(R.layout.ease_widget_chat_primary_menu_1, this);
        editText = findViewById(R.id.et_sendmessage);
        buttonSetModeKeyboard = findViewById(R.id.btn_set_mode_keyboard);
        edittext_layout = findViewById(R.id.edittext_layout);
        buttonSetModeVoice = findViewById(R.id.btn_set_mode_voice);
        buttonSend = findViewById(R.id.btn_send);
        buttonPressToSpeak = findViewById(R.id.btn_press_to_speak);
        faceNormal = findViewById(R.id.iv_face_normal);
        faceChecked = findViewById(R.id.iv_face_checked);
        faceLayout = findViewById(R.id.rl_face);
        buttonMore = findViewById(R.id.btn_more);
        edittext_layout.setBackgroundResource(R.drawable.ease_input_bar_bg_normal);

        buttonSend.setOnClickListener(this);
        buttonSetModeKeyboard.setOnClickListener(this);
        buttonSetModeVoice.setOnClickListener(this);
        buttonMore.setOnClickListener(this);
        faceLayout.setOnClickListener(this);
        editText.setOnClickListener(this);
        editText.requestFocus();

        editText.setOnFocusChangeListener(new View.OnFocusChangeListener() {

            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                if (hasFocus) {
                    edittext_layout.setBackgroundResource(R.drawable.ease_input_bar_bg_active);
                } else {
                    edittext_layout.setBackgroundResource(R.drawable.ease_input_bar_bg_normal);
                }

            }
        });
        // listen the text change
        editText.addTextChangedListener(new TextWatcher() {

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (!TextUtils.isEmpty(s)) {
                    buttonMore.setVisibility(View.GONE);
                    buttonSend.setVisibility(View.VISIBLE);
                } else {
                    buttonMore.setVisibility(View.VISIBLE);
                    buttonSend.setVisibility(View.GONE);
                }

                //   MoonUtils.makeSpannableStringTags(context, s.toString(), 0.6f, ImageSpan.ALIGN_BOTTOM);


            }

            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
                //  MoonUtils.makeSpannableStringTags(context, s.toString(), 0.6f, ImageSpan.ALIGN_BOTTOM);
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });
        InputFilter[] filters = {getInputFilterProhibitEmoji()};
        editText.setFilters(filters);
        buttonPressToSpeak.setOnTouchListener(new View.OnTouchListener() {

            @Override
            public boolean onTouch(View v, MotionEvent event) {
                if (listener != null) {
                    return listener.onPressToSpeakBtnTouch(v, event);
                }
                return false;
            }
        });

//        buttonSetModeVoice.setOnTouchListener(new View.OnTouchListener() {
//            @Override
//            public boolean onTouch(View v, MotionEvent event) {
//                if (listener != null) {
//                    return listener.onPressToSpeakBtnTouch(v, event);
//                }
//                return false;
//            }
//        });
    }


    /**
     * append emoji icon to editText
     *
     * @param emojiContent
     */
    public void onEmojiconInputEvent(CharSequence emojiContent) {
        editText.append(emojiContent);
    }

    /**
     * delete emojicon
     */
    public void onEmojiconDeleteEvent() {
        if (!TextUtils.isEmpty(editText.getText())) {
            KeyEvent event = new KeyEvent(0, 0, 0, KeyEvent.KEYCODE_DEL, 0, 0, 0, 0, KeyEvent.KEYCODE_ENDCALL);
            editText.dispatchKeyEvent(event);
        }
    }

    /**
     * on clicke event
     *
     * @param view
     */
    @Override
    public void onClick(View view) {
        Log.e(TAG, "onClick: 点击回调执行");
        switch (view.getId()) {
            case R.id.btn_send:
                if (listener != null) {
                    String s = editText.getText().toString();
                    editText.setText("");
                    listener.onSendBtnClicked(s);
                }
                break;
            case R.id.btn_set_mode_voice:
                setModeVoice();
                showNormalFaceImage();
                if (listener != null)
                    listener.onToggleVoiceBtnClicked();
                break;
            case R.id.btn_set_mode_keyboard:
                setModeKeyboard();
                showNormalFaceImage();
                if (listener != null)
                    listener.onToggleVoiceBtnClicked();
                break;
            case R.id.btn_more:
                buttonSetModeVoice.setVisibility(View.VISIBLE);
                buttonSetModeKeyboard.setVisibility(View.GONE);
                edittext_layout.setVisibility(View.VISIBLE);
                buttonPressToSpeak.setVisibility(View.GONE);
                editText.setVisibility(View.VISIBLE);
                editText.requestFocus();  //如果不获取焦点的话，首次点击editText时点击事件回调无效，会导致扩展菜单不会被隐藏，当键盘输入被弹出时将其顶到上方
                showNormalFaceImage();
                if (listener != null)
                    listener.onToggleExtendClicked();
                break;
            case R.id.et_sendmessage:
                Log.i(TAG, "onClick: 输入框被点击了！");
                edittext_layout.setBackgroundResource(R.drawable.ease_input_bar_bg_active);
                faceNormal.setVisibility(View.VISIBLE);
                faceChecked.setVisibility(View.INVISIBLE);
                if (listener != null)
                    listener.onEditTextClicked();
                break;
            case R.id.rl_face:
                toggleFaceImage();
                if (listener != null) {
                    listener.onToggleEmojiconClicked();
                }
                break;
        }
    }


    /**
     * show voice icon when speak bar is touched
     */
    protected void setModeVoice() {
        hideKeyboard();
        edittext_layout.setVisibility(View.GONE);
        buttonSetModeVoice.setVisibility(View.GONE);
        buttonSetModeKeyboard.setVisibility(View.VISIBLE);
        buttonSend.setVisibility(View.GONE);
        buttonMore.setVisibility(View.VISIBLE);
        buttonPressToSpeak.setVisibility(View.VISIBLE);
        faceNormal.setVisibility(View.VISIBLE);
        faceChecked.setVisibility(View.INVISIBLE);

    }

    /**
     * show keyboard
     */
    protected void setModeKeyboard() {
        edittext_layout.setVisibility(View.VISIBLE);
        buttonSetModeKeyboard.setVisibility(View.GONE);
        buttonSetModeVoice.setVisibility(View.VISIBLE);
        // editText.requestFocus();
        showKeyboard(editText);
        buttonPressToSpeak.setVisibility(View.GONE);
        if (TextUtils.isEmpty(editText.getText())) {
            buttonMore.setVisibility(View.VISIBLE);
            buttonSend.setVisibility(View.GONE);
        } else {
            buttonMore.setVisibility(View.GONE);
            buttonSend.setVisibility(View.VISIBLE);
        }

    }


    protected void toggleFaceImage() {
        if (faceNormal.getVisibility() == View.VISIBLE) {
            showSelectedFaceImage();
        } else {
            showNormalFaceImage();
        }
    }

    private void showNormalFaceImage() {
        faceNormal.setVisibility(View.VISIBLE);
        faceChecked.setVisibility(View.INVISIBLE);
    }

    private void showSelectedFaceImage() {
        faceNormal.setVisibility(View.INVISIBLE);
        faceChecked.setVisibility(View.VISIBLE);
    }

    public InputFilter getInputFilterProhibitEmoji() {
        InputFilter filter = (source, start, end, dest, dstart, dend) -> MoonUtils.makeSpannableStringTags(context, source.toString(), 0.6f, ImageSpan.ALIGN_CENTER);
        return filter;
    }

    public View getButtonSetModeVoice() {
        return buttonSetModeVoice;
    }

    @Override
    public void onExtendMenuContainerHide() {
        showNormalFaceImage();
    }

    @Override
    public void onTextInsert(CharSequence text) {
        int start = editText.getSelectionStart();
        Editable editable = editText.getEditableText();
        editable.insert(start, text);
        setModeKeyboard();
    }

    @Override
    public EditText getEditText() {
        return editText;
    }


    private void showKeyboard(View view) {
        try {
            InputMethodManager imm = (InputMethodManager) view.getContext()
                    .getSystemService(Context.INPUT_METHOD_SERVICE);
            if (imm != null) {
                view.requestFocus();
                imm.showSoftInput(view, 0);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}
